    $(function (){
    	var contents = []; // 下拉列表内容
    	var key; // 搜索框
    	var zTreeObj ; // zTree 编码
    	var lastValue = "", nodeList = [], fontCss = {};
    	var specCode ; // 临床专业编码
    	var grid = $('[data-role="specCodeGrid"]');
    	var form = $("[name='cliSpecForm']");
   
    // 加载并初始化
    function queryDrgTreeData(specCode,version){
    	$.post(contextPath + "/cliSpec/getDrgTree.dhc",{"specCode":specCode ,"version":version}).done(function(data){
    		 var ztreenode=data.data.data ;
    		 loadZtreeFun(ztreenode) ;
    	}) ;
    }
	// 获取系统配置的版本号
    function getVerCode(versionAll){
    	$.post(contextPath + "/systemConfig/getConfigByCode.dhc" ,{"alterParam":"GROUP_VER"}).done(function(data){
    		var verCode = data.data ;
    		$.each(versionAll,function(i,n){
         	   // 将系统配置的分组器版本置为选中状态
         	   if(n.verCode == verCode){
         		  contents.push({title:n.verDesc, value:n.verCode,selected:true});
         	   } else {
         		  contents.push({title:n.verDesc, value:n.verCode,selected:false});
         	   }
       	  });
    	})
    }
    	
	PageLoader = {
	    initSearchPanel:function(){
	    },
	    initGridPanel: function(){
	         var self = this;
	         var width = 152;
	         /*加载版本号*/
	   	$.get(contextPath + '/DRGVersion/findAllVersion.dhc').done(function(result){
	               if(result.success ){
	                   versionAll = result.data;
	                   getVerCode(versionAll);
	              }
	       });
  		return grid.grid({
            identity:"specCode",
            buttons: [
                    {content: '<button class="btn btn-primary" type="button"><span class="glyphicon glyphicon-plus"><span>添加</button>', action: 'add'},
                    {content: '<button class="btn btn-success" type="button"><span class="glyphicon glyphicon-edit"><span>修改</button>', action: 'modify'},
                    {content: '<button class="btn btn-danger" type="button"><span class="glyphicon glyphicon-remove"><span>删除</button>', action: 'delete'} ,
                    {content: '<button class="btn btn-info" type="button"><span class="glyphicon glyphicon-th-large"><span>选择DRG</button>', action: 'selDrg'}
                ],
            url:contextPath+ "/cliSpec/pageJson.dhc",
            columns: 
        	[
        	 { title: '临床专业代码', name: 'specCode', width: 260},
        	 { title: '临床专业名称', name: 'specDesc', width: 260},
        	 { title: '操作', width: 130, render: function (rowdata, name, index)
                 {
                     var param = '"' + rowdata.specCode + '"';
                     var h = "<a href='javascript:openDrgPage(" + param + ")'>所辖DRG</a> ";
                     return h;
                 }
             },
             { title: '备注', name: 'specMark', width: 260}
            ]
     }).on({
               'add': function(){
                   self.add($(this));
               },
               'modify': function(event, data){
                    var indexs = data.data;
                    var $this = $(this);
                    if(indexs.length == 0){
                    	drgUI.warning('请选择一条记录进行修改');
                        return;
                    }
                    if(indexs.length > 1){
                    	 drgUI.warning('只能选择一条记录进行修改');
                        return ;
                    }
                   self.modify(data.item[0],indexs[0], $this);
                },
               'selDrg': function(event, data){
                    var indexs = data.data;
                    var $this = $(this);
                    if(indexs.length == 0){
                        drgUI.warning('请选择一条记录进行操作');
                        return;
                    }
                    if(indexs.length > 1){
                    	drgUI.warning('只能选择一条记录进行操作');
                        return;
                    }
                   self.selDrg(data.item[0],indexs[0], $this);
                },
                
               'delete': function(event, data){
                    var indexs = data.data;
                    var $this = $(this);
                    if(indexs.length == 0){
                       drgUI.warning('请选择要删除的记录');
                        return;
                    }
                    var remove = function(){
                        self.remove(indexs, $this);
                    };
                    drgUI.confirm({
                        content: '删除临床专业会同时删除与DRG的关系，确定要删除所选记录吗?',
                        callSure: remove
                    });
                    
               }
     });
	    },
	    add: function(grid){
	        var self = this;
	        var dialog = $('<div class="modal fade"><div class="modal-dialog">'
	        	+'<div class="modal-content"><div class="modal-header"><button type="button" class="close" '
	        	+'data-dismiss="modal" aria-hidden="true">&times;</button>'
	        	+'<h4 class="modal-title">新增</h4></div><div class="modal-body">'
	        	+'<p>One fine body&hellip;</p></div><div class="modal-footer">'
	        	+'<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>'
	        	+'<button type="button" class="btn btn-success" id="save">保存</button></div></div>'
	        	+'</div></div>');
	        $.get(contextPath + '/pages/cliSpec/cliSpec-add.jsp').done(function(html){
	            dialog.modal({
	                keyboard:false
	            }).on({
	                'hidden.bs.modal': function(){
	                    $(this).remove();
	                }
	            }).find('.modal-body').html(html);
	            self.initPage(dialog.find('form'));
	        });
	        dialog.find('#save').on('click',{grid: grid}, function(e){
	              if(!Validator.Validate(dialog.find('form')[0],3))return;
	              var specCode = $("#specCodeID").val();
	              $.post(contextPath + '/cliSpec/isCodeExist.dhc',{'specCode':specCode}).done(function(result){
	            	  if(result){
	                         drgUI.error('编码已存在，请重新输入');
	            	  }else{
	            		  $.post(contextPath + '/cliSpec/save.dhc', dialog.find('form').serialize()).done(function(result){
		   	                   if(result.success ){
		   	                        dialog.modal('hide');
		   	                        e.data.grid.data('koala.grid').refresh();
		   	                        drgUI.success('保存成功！');
		   	                    }else{
		   	                        drgUI.error('保存失败,'+result.errorMessage);
		   	                     }
		   	              	});
	            	  }
	              });
	        });
	    },
	    
	    modify: function(item,id, grid){
	        var self = this;
	        var dialog = $('<div class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h4 class="modal-title">修改</h4></div><div class="modal-body"><p>One fine body&hellip;</p></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button><button type="button" class="btn btn-success" id="save">保存</button></div></div></div></div>');
	        $.get(contextPath + '/pages/cliSpec/cliSpec-update.jsp').done(function(html){
	               dialog.find('.modal-body').html(html);
	               self.initPage(dialog.find('form'));
	               dialog.find("#specCodeIDUpdate").val($.trim(item.specCode));
	               dialog.find("#specDescIDUpdate").val(item.specDesc);
	               dialog.find("#specMarkIDUpdate").val(item.specMark);
	                dialog.modal({
	                    keyboard:false
	                }).on({
	                    'hidden.bs.modal': function(){
	                        $(this).remove();
	                    }
	                });
	                dialog.find('#save').on('click',{grid: grid}, function(e){
	                  if(!Validator.Validate(dialog.find('form')[0],3))return;
	  	            // 如果有编号重复提醒不能保存(改回原来的编码的除外),如果编码改过了就进行验证，否则不验证，直接更新
	                var dataModify ={"specCode":$("#specCodeIDUpdate").val(),"specDesc":$("#specDescIDUpdate").val(),"specMark":$("#specMarkIDUpdate").val()} ;  
	            		 $.post(contextPath + '/cliSpec/save.dhc?', dataModify).done(function(result){
	                        if(result.success){
	                            dialog.modal('hide');
	                            e.data.grid.data('koala.grid').refresh();
      	                        drgUI.success('保存成功!');
	                        }else{
	                            drgUI.error(result.actionError);
	                        }
	                    });
	               });
	        });
	    },
	   
	    selDrg: function(item,id, grid){
	        var self = this;
	        specCode = item['specCode'] ;
	        var dialog = $('<div class="modal fade"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h4 class="modal-title">选择DRG</h4></div><div class="modal-body"><p>One fine body&hellip;</p></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button><button type="button" class="btn btn-success" id="save">保存</button></div></div></div></div>');
	        $.get(contextPath + '/pages/cliSpec/drg-select.jsp').done(function(html){
	               dialog.find('.modal-body').html(html);
	               self.initPage(dialog.find('form'));
	               dialog.find(".modal-dialog").css("width","640px");
		           dialog.find(".modal-footer").css("margin-top","0px");
		       	   dialog.find("#echartcq4").css("width","600px");
	               dialog.modal({
	                    keyboard:false
	                }).on({
	                	"shown.bs.modal":function(){
	                         queryDrgTreeData(specCode,$('#versionCodeID > input[type="hidden"]').val());
	                	},
	                    'hidden.bs.modal': function(){
	                        $(this).remove();
	                    }
	                });
	               // 搜索框功能
	                 key = dialog.find('#searchDiv > span > input') ;
	                 key.bind("focus", focusKey)
	     			.bind("blur", blurKey)
	     			.bind("propertychange", searchNode)
	     			.bind("input", searchNode);
	                 // 选择drg后保存
	                 dialog.find('#save').on('click',{grid: grid}, function(e){
	                	var drgs  ;
	                	var nodes = zTreeObj.getCheckedNodes(true) ;
	                	var arrList = new Array() ;
	                	// 过滤非子节点
	                	for (var i = 0; i < nodes.length; i++) {
	                		if(nodes[i].level == 2 ){
	                			arrList.push(nodes[i].id);
	                		}
	                	}
	                	// 保存失效的子节点
	                	var nodesAll = zTreeObj.transformToArray(zTreeObj.getNodes());
	                	for(var i = 0 ; i < nodesAll.length ; i ++) {
	                		if(nodesAll[i].chkDisabled){
	                			arrList.push(nodesAll[i].id);
	                		}
	                	}
	                	var version = $('#versionCodeID > input[type="hidden"]').val() ;
	                	if( version == ""){
	  	                     drgUI.error('请选择DRG版本');
	  	            	} else {
	  	            		$.post(contextPath + '/cliSpec/saveDrgsNode.dhc',  {"specCode":specCode,"version":version,"drgs":arrList}).done(function(result){
		                         if(result.success){
		                            dialog.modal('hide');
		                            e.data.grid.data('koala.grid').refresh();
		                            drgUI.success('保存成功,清除缓存后分析页面生效');
		                        }else{
		                            drgUI.error('result.actionError');
		                        } 
		                    });
	  	            	 }
	               });
	        });
	    },
	    
	    initPage: function(form){
	              form.find('.form_datetime').datetimepicker({
	                   language: 'zh-CN',
	                   format: "yyyy-mm-dd",
	                   autoclose: true,
	                   todayBtn: true,
	                   minView: 2,
	                   pickerPosition: 'bottom-left'
	               }).datetimepicker('setDate', new Date()); //加载日期选择器
	              form.find('.select').each(function(){
	                    var select = $(this);
	                    var idAttr = select.attr('id');
	                    select.select({
	                        title: '请选择',
	                        contents: contents 
	                    }).on('change', function(){
	                    	// 将搜索框置空
	                    	$("#searchDiv > span > input").val("") ;
	                        form.find('#'+ idAttr + '_').val($(this).getValue());
	                        var version = $(this).getValue() ;
	                        queryDrgTreeData(specCode,version);
	                    });
	               });
	    },
	    remove: function(ids, grid){
	    	var data = [{ name: 'specCodes', value: ids.join('】【') }];
	    	$.post(contextPath + '/cliSpec/delete.dhc', data).done(function(result){
	    		var msg = result.data.data ;
                    if(result.success){
                        grid.data('koala.grid').refresh();
                        if(msg == null || msg == ""){
                            drgUI.success('删除成功')
                        } else {
                             drgUI.error(msg + "已被科室选择,取消选择后才能删除");
                        }
                    } 
	    	});
	    }
	}
	PageLoader.initSearchPanel();
	PageLoader.initGridPanel();
	form.find('#search').on('click', function(){
            if(!Validator.Validate(document.getElementById(formId),3)){
             	return;
            }
            var params = {};
            form.find('input').each(function(){
                var $this = $(this);
                var name = $this.attr('name');
                if(name){
                    params[name] = $this.val();
                }
            });
            grid.getGrid().search(params);
        });
	
	
	// 加载ztree
	var loadZtreeFun = function(ztreenode) {
		var fontCss = {};
		var setting = {
		        data:{
		            simpleData:{
		         	 enable: true,
		         	 idKey:  "id",
		         	 pIdKey: "pid",
		         	 rootPId:"0"
		            }  
		        },  
		        check: {
		            enable: true 
		        },
		        view :{ 
		            showIcon: false,  
		            fontCss: getFontCss
		        }  
		};
		
		function getFontCss(treeId, treeNode) {
			return (!!treeNode.highlight) ? {color:"#6633FF", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
		}
		zTreeObj = $.fn.zTree.init($("#drgTree"),setting,ztreenode) ;
	}
	
	function focusKey(e) {
		if (key.hasClass("empty")) {
			key.removeClass("empty");
		}
	}
	function blurKey(e) {
		if (key.get(0).value === "") {
			key.addClass("empty");
		}
	}
	// 搜索drg
	function searchNode(e) {
			var value = $.trim(key.get(0).value);
			var keyType = "name";
			if (key.hasClass("empty")) {
				value = "";
			}
			if (lastValue === value) return;
			lastValue = value ;
			updateNodes(false);
			nodeList = zTreeObj.getNodesByParamFuzzy(keyType, value);
			if (value == "" || nodeList.length == 0 ) {
				zTreeObj.expandAll(false);
				return;
			}
		    updateNodes(true);
	}
	// 更新节点高亮状态
	function updateNodes(highlight) {
		for( var i=0, l=nodeList.length; i<l; i++) {
			nodeList[i].highlight = highlight;
			zTreeObj.updateNode(nodeList[i]);
			// 展开搜索到的节点的父节点
			// 设置focus = true 表示 展开 / 折叠 操作后，通过设置焦点保证此焦点进入可视区域内
			var focus = false ;
			if( i == 0 && highlight ) {
				focus = true ;
			} 
			zTreeObj.expandNode(nodeList[i].getParentNode(),highlight,focus,false);
		}
	}
	
	function filter(node) {
		return !node.isParent && node.isFirstNode;
	}
	
});
 
var openDrgPage = function(specCode){
        var dialog = $('<div class="modal fade"><div class="modal-dialog" role="document" style="width:800px;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h4 class="modal-title">查看DRG</h4></div><div class="modal-body"><p>One fine body&hellip;</p></div><div class="modal-footer"><button type="button" class="btn btn-info" data-dismiss="modal">返回</button></div></div></div></div>');
        dialog.modal({
            keyboard:false
        }).on({
            'hidden.bs.modal': function(){
                $(this).remove();
            } ,
            'shown.bs.modal':function() {
            	$.get(contextPath + '/pages/cliSpec/cliSpec-view.jsp').done(function(html){
                    dialog.find('.modal-body').html(html);
                    $.get( contextPath + '/cliSpec/findDrgsBySpec/' + specCode + '.dhc').done(function(data){
                 	   var data_0 = data.data.data
                 	   var versionTabContent = dialog.find('#versionTabContent');
                 	   if(data_0.length == 0){
                 		   dialog.find('.modal-body').html('<p class="text-center"> 无数据 </p>') ;
                 	   } else {
                 		   for(var i = 0 ; i < data_0.length ; i++ ) {
                         	   var table1 = $('<div class="tab-pane fade in active" id="version'+i+'"><table id="tabver'+i+'" class="table table-hover"><thead><tr><th>DRG代码</th><th>DRG描述</th><th>ADRG代码</th><th>ADRG描述</th><th>MDC代码</th></tr></thead></table></div>') ;
                         	   var table2 = $('<div class="tab-pane fade " id="version'+i+'"><table id="tabver'+i+'" class="table table-hover"><thead><tr><th>DRG代码</th><th>DRG描述</th><th>ADRG代码</th><th>ADRG描述</th><th>MDC代码</th></tr></thead></table></div>') ;
                         	   versionTabContent = dialog.find('#versionTabContent');
                                var versionTab = dialog.find('#versionTab') ;
                                    if(i>0){
                                 	   versionTab.append($('<li><a href="#version'+i+'" data-toggle="tab">'+data_0[i].verDesc+'</a></li>'));
                                 	   versionTabContent.append(table2);
                                    } else {
                                 	   versionTab.append($('<li class="active"><a href="#version'+i+'" data-toggle="tab">'+data_0[i].verDesc+'</a></li>'));
                                 	   versionTabContent.append(table1);
                                    }
                                    data = data_0[i].drgsList ; 
                                    var columns=[
        											{
        												"data": "DRG_CODE",
        						                		  "render": function(obj, type, full){
        						                			  if(full.DRG_CODE){
        						                				  return full.DRG_CODE ;
        						                			  } else {
        						                				  return " - " ;
        						                			  }
        						                		  }
        											},
        											{
        												"data": "DRG_DESC",
	      						                		 "render": function(obj, type, full){
	    						                			 if(full.DRG_DESC){
	    						                				 return full.DRG_DESC ;
	    						                			 } else {
	    						                				 return " - " ;
	    						                			 }
	    						                		  }
        											},
        											{
        												"data": "ADRG_CODE"
        											},
        											{
        												"data": "ADRG_DESC"
        											},
        											{
        												"data": "MDC_CODE"
        											}
                          					   ]
                                    var paramsDataTables={searching:false};
                                    dialog.find('#tabver'+i+'').dataTableBasic(columns,data,paramsDataTables);
                     	   }
                 	    }
                   });
             });
            }
        });
        
}